package com.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 描述:
 * 生产者消费者
 * @author luzhongfu
 * Created by lucky on 2020-06-01 1:44 PM
 */
public class ProducerAndConsumer {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        Godown godown = new Godown();
        executorService.execute(new Producer(godown,10));
        executorService.execute(new Producer(godown,50));
        executorService.execute(new Consumer(godown,70));
        executorService.execute(new Consumer(godown,10));
        executorService.execute(new Producer(godown,60));
        executorService.execute(new Consumer(godown,50));
        executorService.shutdown();
    }


    static class Producer implements Runnable{

        private Godown godown;

        private int x;

        public Producer(Godown godown, int x) {
            this.godown = godown;
            this.x = x;
        }

        @Override
        public void run() {
            godown.produce(x);
        }
    }

    static class Consumer implements Runnable{

        private Godown godown;

        private int x;

        public Consumer(Godown godown, int x) {
            this.godown = godown;
            this.x = x;
        }

        @Override
        public void run() {
            godown.consume(x);
        }
    }
    static class Godown{

        private int max = 100;

        private int count;

        public synchronized void consume(int item){
            try {
                if(count < item){
                    wait();
                }else{
                    count = count - item;
                    System.out.println("消费了 item:"+item + " count"+count);
                }

            }catch (Exception e){

            }finally {
                notify();
            }
        }

        public synchronized void produce(int item){
            if(count + item > max){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count = count + item;
            System.out.println("生产了 item:"+item + " count:"+count);
            notify();
        }
    }
}
